Tree Data Structure

This introductory guide to Tree Data Structures, you will explore the foundational principles of Tree, understand their significance and applications, discover effective strategies for learning, and step-by-step journey for beginners.

Overveiw

Chapters

1 Chapter are there in this module reguarding tree data structures.

Start Learning

Quiz

Quiz on the topics being learnt in this module to ensure your knowldege.

Take Quiz

Problems

Practice Problems on the topics being covered in this module

See Problems

Chapters

Introduction to Binary Tree

Binary tree is a tree data structure (non-linear) in which each node can have at most two children which are referred to as the left child and the right child.

The topmost node in a binary tree is called the root, and the bottom-most nodes are called leaves. A binary tree can be visualized as a hierarchical structure with the root at the top and the leaves at the bottom.

Representation of Binary Tree

Each node in a Binary Tree has three parts:

  • Data
  • Pointer to the left child
  • Pointer to the right child



Below is the representation of a Node of Binary Tree in different languages:

Using "struct" to make user-defined data type


struct node {
  int data;
  struct node* left;
  struct node* right;
};
      

Using "class" to make user-defined data type


class Node {
public:
  int data;
  Node* left;
  Node* right;
};
      



Types of Binary Tree

Binary Tree can be classified into multiple types based on several factors:

On the basis of Number of Children

  • Full Binary Tree
  • Degenerate Binary Tree
  • Skewed Binary Trees

On the basis of Completion of Levels

  • Complete Binary Tree
  • Perfect Binary Tree
  • Balanced Binary Tree

On the basis of Node Values

  • Binary Search Tree
  • AVL Tree
  • Red Black Tree
  • B Tree
  • B+ Tree
  • Segment Tree

Operations On Binary Tree

1. Insertion in Binary Tree

We can insert a node anywhere in a binary tree by inserting the node as the left or right child of any node or by making the node as root of the tree.

Algorithm to insert a node in a Binary Tree:

  • Check if there is a node in the binary tree, which has missing left child. If such a node exists, then insert the new node as its left child.
  • Check if there is a node in the binary tree, which has missing right child. If such a node exists, then insert the new node as its right child.
  • If we don’t find any node with missing left or right child, then find the node which has both the children missing and insert the node as its left or right child.



2. Traversal of Binary Tree

Traversal of Binary Tree involves visiting all the nodes of the binary tree. Tree Traversal algorithms can be classified broadly into two categories:

Depth-First Search (DFS) Algorithms

  • Preorder Traversal (current-left-right): Visit the current node before visiting any nodes inside the left or right subtrees. Here, the traversal is root – left child – right child. It means that the root node is traversed first then its left child and finally the right child.
  • Inorder Traversal (left-current-right): Visit the current node after visiting all nodes inside the left subtree but before visiting any node within the right subtree. Here, the traversal is left child – root – right child. It means that the left child is traversed first then its root node and finally the right child.
  • Postorder Traversal (left-right-current): Visit the current node after visiting all the nodes of the left and right subtrees. Here, the traversal is left child – right child – root. It means that the left child has traversed first then the right child and finally its root node.

Breadth-First Search (BFS) Algorithms

  • Level Order Traversal: Visit nodes level-by-level and left-to-right fashion at the same level. Here, the traversal is level-wise. It means that the most left child has traversed first and then the other children of the same level from left to right have traversed.



3. Deletion in Binary Tree

We can delete any node in the binary tree and rearrange the nodes after deletion to again form a valid binary tree.

Algorithm to delete a node in a Binary Tree:

  • Starting at the root, find the deepest and rightmost node in the binary tree and the node which we want to delete.
  • Replace the deepest rightmost node’s data with the node to be deleted.
  • Then delete the deepest rightmost node.



4. Searching in Binary Tree

We can search for an element in the node by using any of the traversal techniques.

Algorithm to search a node in a Binary Tree:

  • Start from the root node.
  • Check if the current node’s value is equal to the target value.
  • If the current node’s value is equal to the target value, then this node is the required node.
  • Otherwise, if the node’s value is not equal to the target value, start the search in the left and right child.
  • If we do not find any node whose value is equal to target, then the value is not present in the tree.



Auxiliary Operations On Binary Tree

  • Finding the height of the tree
  • Find level of a node in a Binary tree
  • Finding the size of the entire tree



Implementation of Binary Tree

Below is the code for insertion, deletion and traversal of the binary tree:


#include <bits/stdc++.h>
using namespace std;

// Node class to define the structure of the node
class Node {
public:
  int data;
  Node *left, *right;
  // Parameterized Constructor
  Node(int val)
  {
      data = val;
      left = right = NULL;
  }
};

// Function to insert nodes
Node* insert(Node* root, int data)
{
  // If tree is empty, new node becomes the root
  if (root == NULL) {
      root = new Node(data);
      return root;
  }
  // queue to traverse the tree and find the position to
  // insert the node
  queue<Node*> q;
  q.push(root);
  while (!q.empty()) {
      Node* temp = q.front();
      q.pop();
      // Insert node as the left child of the parent node
      if (temp->left == NULL) {
          temp->left = new Node(data);
          break;
      }
      // If the left child is not null push it to the
      // queue
      else
          q.push(temp->left);
      // Insert node as the right child of parent node
      if (temp->right == NULL) {
          temp->right = new Node(data);
          break;
      }
      // If the right child is not null push it to the
      // queue
      else
          q.push(temp->right);
  }
  return root;
}

/* function to delete the given deepest node
(d_node) in binary tree */
void deletDeepest(Node* root, Node* d_node)
{
  queue<Node*> q;
  q.push(root);
  // Do level order traversal until last node
  Node* temp;
  while (!q.empty()) {
      temp = q.front();
      q.pop();
      if (temp == d_node) {
          temp = NULL;
          delete (d_node);
          return;
      }
      if (temp->right) {
          if (temp->right == d_node) {
              temp->right = NULL;
              delete (d_node);
              return;
          }
          else
              q.push(temp->right);
      }
      if (temp->left) {
          if (temp->left == d_node) {
              temp->left = NULL;
              delete (d_node);
              return;
          }
          else
              q.push(temp->left);
      }
  }
}

/* function to delete element in binary tree */
Node* deletion(Node* root, int key)
{
  if (!root)
      return NULL;
  if (root->left == NULL && root->right == NULL) {
      if (root->data == key)
          return NULL;
      else
          return root;
  }
  queue<Node*> q;
  q.push(root);
  Node* temp;
  Node* key_node = NULL;
  // Do level order traversal to find deepest
  // node(temp) and node to be deleted (key_node)
  while (!q.empty()) {
      temp = q.front();
      q.pop();
      if (temp->data == key)
          key_node = temp;
      if (temp->left)
          q.push(temp->left);
      if (temp->right)
          q.push(temp->right);
  }
  if (key_node != NULL) {
      int x = temp->data;
      key_node->data = x;
      deletDeepest(root, temp);
  }
  return root;
}

// Inorder tree traversal (Left - Root - Right)
void inorderTraversal(Node* root)
{
  if (!root)
      return;
  inorderTraversal(root->left);
  cout << root->data << " ";
  inorderTraversal(root->right);
}

// Preorder tree traversal (Root - Left - Right)
void preorderTraversal(Node* root)
{
  if (!root)
      return;
  cout << root->data << " ";
  preorderTraversal(root->left);
  preorderTraversal(root->right);
}

// Postorder tree traversal (Left - Right - Root)
void postorderTraversal(Node* root)
{
  if (root == NULL)
      return;
  postorderTraversal(root->left);
  postorderTraversal(root->right);
  cout << root->data << " ";
}

// Function for Level order tree traversal
void levelorderTraversal(Node* root)
{
  if (root == NULL)
      return;

  // Queue for level order traversal
  queue<Node*> q;
  q.push(root);
  while (!q.empty()) {
      Node* temp = q.front();
      q.pop();
      cout << temp->data << " ";
      // Push left child in the queue
      if (temp->left)
          q.push(temp->left);
      // Push right child in the queue
      if (temp->right)
          q.push(temp->right);
  }
}

/* Driver function to check the above algorithm. */
int main()
{
  Node* root = NULL;
  // Insertion of nodes
  root = insert(root, 10);
  root = insert(root, 20);
  root = insert(root, 30);
  root = insert(root, 40);

  cout << "Preorder traversal: ";
  preorderTraversal(root);

  cout << "\nInorder traversal: ";
  inorderTraversal(root);

  cout << "\nPostorder traversal: ";
  postorderTraversal(root);

  cout << "\nLevel order traversal: ";
  levelorderTraversal(root);

  // Delete the node with data = 20
  root = deletion(root, 20);

  cout << "\nInorder traversal after deletion: ";
  inorderTraversal(root);
  return 0;
}
      

Output

Preorder traversal: 10 20 40 30

Inorder traversal: 40 20 10 30

Postorder traversal: 40 20 30 10

Level order traversal: 10 20 30 40

Inorder traversal after deletion: 40 10 30




Complexity Analysis of Binary Tree Operations

Operations Time Complexity Space Complexity
Insertion O(N) O(N)
Preorder Traversal O(N) O(N)
Inorder Traversal O(N) O(N)
Postorder Traversal O(N) O(N)
Level Order Traversal O(N) O(N)
Deletion O(N) O(N)
Searching O(N) O(N)

We can use Morris Traversal to traverse all the nodes of the binary tree in O(n) time complexity but with O(1) space complexity.